# import json
# import math
# import os.path
# import pathlib
import pathlib

import requests
import platform

URL = 'http://47.92.105.5:19002/getBookingPayTask'
URL1 = 'http://47.92.105.5:19002/bookingPayTaskResult'


def get_resp():
    person_list = []
    # data = {
    #     "clientType": "U2_IOS_APP_BOOKING_CLIENT",
    #     "machineCode": "U2-IOS-App-Pay"
    # }
    # try:
    #     resp = requests.post(URL, json=data)
    # except Exception as e:
    #     raise e
    # assert resp.json()['status'] == 'Y', f"实际返回：{resp.text}"
    # print(resp.json())
    # d = resp.json()['data']
    d = {'id': 6456360, 'status': 300, 'orderNo': '972281173', 'xorderNo': None, 'orderPnr': '1N1IA8',
          'orderCPnr': None, 'orderInfoId': 7355946, 'modifyPriceType': 99, 'orderTripId': '7620245',
          'matchRuleId': 1449, 'sourceId': None, 'source': '2', 'carrier': 'U2', 'depAirport': 'BHD',
          'arrAirport': 'LTN', 'depCity': 'BFS', 'arrCity': 'LON', 'depDate': '2023-06-26', 'arrDate': None,
          'depFlightNumber': 'U2646', 'arrFlightNumber': None, 'tripType': 1, 'runWay': 1, 'passengerCount': 1,
          'availableSeatCount': None, 'point': 0, 'sourceCurrency': 'GBP', 'sourcePrice': 77.0, 'targetPrice': 76.99,
          'targetCurrency': 'GBP', 'upPrice': 0.0, 'displayPrice': 1050.0, 'startTime': '2023-06-18T09:51:32.000+0000',
          'bookingClient': 'U2_IOS_APP_BOOKING_CLIENT', 'payClient': 'U2_IOS_APP_BOOKING_CLIENT', 'remark': None,
          'bookingType': '1', 'depFreeWeight': 0, 'arrFreeWeight': 0, 'retryTimes': 0, 'expectRetryTimes': 0,
          'targetBrushPrice': 76.99, 'webPrice': None, 'tradeOrderId': None, 'firstTask': True, 'brushHours': None,
          'cabinDownTask': False, 'inventoryType': 'NORMAL', 'sellkey': None, 'orderSource': None, 'productClass': None,
          'bigCustomerId': None, 'bigCustomerCode': None, 'contrastPriceInfo': None, 'printPrice': None, 'cabin': 'Y',
          'locale': None, 'passengerVOList': [
         {'id': 11114514, 'payTaskId': None, 'name': 'SHAO/WENXUAN', 'sex': 'F', 'birthday': '1999-06-27',
          'nationality': 'CN', 'cardNum': 'E83164253', 'cardExpired': '20260727', 'cardIssuePlace': 'CN',
          'cardType': 'PP', 'baggageWeight': 23, 'baggagePrice': 306.0, 'baggageWeightStr': None, 'passengerType': None,
          'seatNo': None, 'ticketBaggageWeight': 0, 'ticketBaggageCount': 0, 'ticketBaggagePrice': 0.0,
          'freeBaggageWeight': 0, 'freeBaggageCount': 0, 'freeBaggagePrice': 0, 'packBaggageWeight': 23,
          'packBaggageCount': 0, 'packBaggagePrice': 306.0, 'webIndex': None, 'baggageTargetPrice': None}],
          'returnPassengerVOList': None, 'payPaymentInfoVo': {'name': 'U2-IOS大卡支付', 'airline': 'U2', 'cardVO': None,
                                                              'agentAccountVo': {'id': 356, 'airline': 'U2',
                                                                                 'name': 'ApplePay', 'type': 'AGENT',
                                                                                 'currency': 'USD',
                                                                                 'loginAccount': 'ApplePay',
                                                                                 'loginPassword': '1', 'loginUrl': '1',
                                                                                 'linkEmail': '1',
                                                                                 'linkPhone': '18911690163',
                                                                                 'linkEmailPassword': '1'}},
          'contactVO': {'airline': 'U2', 'linkEmail': '43a65cfe2f0846@creazyair.shop',
                        'linkEmailPassword': 'Aa1)bJ8WWC', 'linkPhone': '15134722741', 'contactName': 'SHAO/WENXUAN'},
          'contacts': {'airline': 'U2', 'linkEmail': '1', 'linkEmailPassword': '1', 'linkPhone': '18911690163',
                       'contactName': 'SHAO/WENXUAN'},
          'memberVO': {'airline': 'U2', 'userName': '43a65cfe2f0846@creazyair.shop', 'password': 'Aa1)bJ8WWC',
                       'promo': None, 'rewarduId': None, 'linkPhone': None, 'accountType': '66',
                       'accountPointNeed': None}, 'promoVO': None,
          'pnrVO': {'id': None, 'payTaskId': 6456360, 'status': None, 'errorType': 1, 'errorMessage': None,
                    'accountUsername': '43a65cfe2f0846@creazyair.shop', 'accountPassword': 'Aa1)bJ8WWC',
                    'linkEmailPassword': 'Aa1)bJ8WWC', 'nameList': ['SHAO/WENXUAN'], 'accountType': 'MEMBER', 'pnr': '',
                    'bigPnr': None, 'sourceCur': 'GBP', 'targetCur': 'GBP', 'ticketAmount': 0.0, 'baggagePrice': None,
                    'baggageCur': None, 'webPrice': None, 'linkEmail': '43a65cfe2f0846@creazyair.shop',
                    'linkPhone': '15134722741', 'verifyPnrPrice': None, 'verifyPnrCur': None,
                    'verifyPnrBaggagePrice': None, 'promo': None, 'machineCode': None, 'clientType': None,
                    'checkStatus': True, 'needPnrVerifyStatus': True, 'createTaskStatus': True,
                    'needRetToPlatform': True, 'itineraryPnrList': None, 'paymentVoList': [
                  {'id': 6577246, 'orderPnrId': None, 'payChannel': 1, 'payType': 1, 'orderNo': '972281173',
                   'orderPayTaskId': 6456360, 'cardName': 'ApplePay', 'cardNumber': 'ApplePay',
                   'settlementAmount': None, 'settlementCurrency': None, 'remark': None, 'del': 0, 'createTime': None}],
                    'badMemberAccount': False, 'pointLeft': None, 'accountSlotLeft': None, 'sellkey': None,
                    'submitSellkey': None, 'orderSource': None, 'tradeOrderId': None, 'expiryTime': None,
                    'holdTimes': None, 'holdTimesLimit': None, 'autoBrushTask': False, 'memberStatus': None,
                    'availableSeatCount': None, 'payUrl': None, 'nextStepClient': None, 'passengerList': None,
                    'channelOrderNo': None, 'cabin': None, 'depPayAmount': None, 'retPayAmount': None,
                    'depBagAmount': None, 'retBagAmount': None}, 'segmentVOList': [
         {'id': 7827600, 'tripId': '7620245', 'depAirport': 'BHD', 'arrAirport': 'LTN', 'depDate': '202306261230',
          'arrDate': '202306261350', 'flightNumber': 'U2646', 'cabin': 'Y', 'segmentIndex': 1, 'childCabin': None}],
          'arrSegmentVOList': None, 'voucherVoList': [], 'sellKeyList': None, 'xOrderPayTaskVo': None}

    luggage_15 = 0
    luggage_23 = 0
    for item in d["passengerVOList"]:
        if not is_eighteen(item['birthday'], d['depDate']):
            print(f"乘客{item['name']}未满18岁！")
            continue
        person_list.append({
            "title": 'Mr' if item["sex"] == 'M' else 'Ms',
            "first_name": item["name"].split('/')[1],
            'last_name': item["name"].split('/')[0],
            'age': '18+'
        })
        if int(item['baggageWeight']) % 15 == 0:
            n = int(item['baggageWeight']) // 15
            luggage_15 += n
        elif int(item['baggageWeight']) % 23 == 0:
            n = int(item['baggageWeight']) // 23
            luggage_23 += n
        else:
            raise Exception("该行李重量选择不支持，当前仅支持15/23两种重量的选择")
    order_info = {
        "user": d['memberVO']['userName'],
        'passwd': d['memberVO']['password'],
        "from_city_code": d['depAirport'],
        "to_city_code": d['arrAirport'],
        'date': d['depDate'],
        "count": len(d["passengerVOList"]),
        'passengers': person_list,
        'flight_num': f"{d['depFlightNumber'][2:]}",
        "luggage_num": [luggage_15, luggage_23],
        "target_currency": d['targetCurrency'],
        "target_price": d['targetPrice']

    }
    # card_info = {
    #     "card_num": d['payPaymentInfoVo']["cardVO"]["cardNumber"],
    #     "card_expire": d['payPaymentInfoVo']["cardVO"]["cardExpired"],
    #     "cvv": d['payPaymentInfoVo']["cardVO"]["cvv"],
    #     'payer': d['payPaymentInfoVo']["cardVO"]["lastName"]
    #
    # }
    pnr_vo: dict = d['pnrVO']
    pnr_vo['passengerList'] = []
    for item in d['passengerVOList']:
        pnr_vo['passengerList'].append({
            "id": item['id'],
            "ownerPnr": ""
        })
    # return order_info, card_info, pnr_vo
    return order_info, pnr_vo


def push_info(pnr_vo: dict):

    pnr_vo['clientType'] = "U2_IOS_APP_BOOKING_CLIENT"
    pnr_vo['machineCode'] = "U2-IOS-App-Pay"

    print('请求内容：')
    print(pnr_vo)
    try:
        resp = requests.post(URL1, json=pnr_vo)
    except Exception as e:
        raise e
    print(resp.text)
    return


def is_eighteen(birth, dep_date):
    import datetime
    birth_d = datetime.datetime.strptime(birth, "%Y-%m-%d")
    today_d = datetime.datetime.strptime(dep_date, "%Y-%m-%d")
    birth_t = birth_d.replace(year=today_d.year)
    if today_d > birth_t:
        age = today_d.year - birth_d.year
    else:
        age = today_d.year - birth_d.year - 1

    if age >= 16:
        return True
    return False


def say(s: str):
    if platform.system().lower() == 'windows':
        ps = pathlib.Path(__file__).parents
        s = pathlib.Path(__file__).joinpath(ps[0],'sound','s1.wav')
        import winsound as ws
        ws.PlaySound(f"{s}", ws.SND_FILENAME)
    elif platform.system().lower() == 'darwin':
        import mac_say
        mac_say.say(s)
    else:
        raise SystemError("暂不支持的系统")




if __name__ == '__main__':
    # get_resp()
    p = {'id': None, 'payTaskId': 6447632, 'status': None, 'errorType': 1, 'errorMessage': None,
         'accountUsername': '33feac4b68d944@redlightok.work', 'accountPassword': 'Aa1)01zlbb',
         'linkEmailPassword': 'Aa1)01zlbb', 'nameList': ['WAKAMATSU/TORU', 'FUJINO/HINAKO'],
         'accountType': 'MEMBER', 'pnr': '', 'bigPnr': None, 'sourceCur': 'EUR', 'targetCur': 'EUR',
         'ticketAmount': 0.0, 'baggagePrice': None, 'baggageCur': None, 'webPrice': None,
         'linkEmail': '33feac4b68d944@redlightok.work', 'linkPhone': '15195479506', 'verifyPnrPrice': None,
         'verifyPnrCur': None, 'verifyPnrBaggagePrice': None, 'promo': None, 'machineCode': None,
         'clientType': None, 'checkStatus': True, 'needPnrVerifyStatus': True, 'createTaskStatus': True,
         'needRetToPlatform': True, 'itineraryPnrList': None, 'paymentVoList': [
            {'id': 6568059, 'orderPnrId': None, 'payChannel': 1, 'payType': 1, 'orderNo': '971862201',
             'orderPayTaskId': 6447632, 'cardName': 'ApplePay', 'cardNumber': 'ApplePay',
             'settlementAmount': None, 'settlementCurrency': None, 'remark': None, 'del': 0, 'createTime': None}],
         'badMemberAccount': False, 'pointLeft': None, 'accountSlotLeft': None, 'sellkey': None,
         'submitSellkey': None, 'orderSource': None, 'tradeOrderId': None, 'expiryTime': None,
         'holdTimes': None, 'holdTimesLimit': None, 'autoBrushTask': False, 'memberStatus': None,
         'availableSeatCount': None, 'payUrl': None, 'nextStepClient': None, 'passengerList': None,
         'channelOrderNo': None, 'cabin': None, 'depPayAmount': None, 'retPayAmount': None,
         'depBagAmount': None, 'retBagAmount': None
         }

    p['status'] = 450
    p['pnr'] = 'K5LLBXS'
    p['ticketAmount'] = 58.00
    p['depPayAmount'] = 58.00
    p['depBagAmount'] = 145.96
    push_info(p)
